from rest_framework import serializers
from .models import Article, Category, Tag


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name', 'slug']


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['id', 'name', 'slug']


class ArticleSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True)  # 显示作者字符串
    category = CategorySerializer(read_only=True)
    category_id = serializers.PrimaryKeyRelatedField(
        queryset=Category.objects.all(), source='category', write_only=True, required=False, allow_null=True)
    tags = TagSerializer(many=True, read_only=True)
    tag_ids = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all(), many=True, source='tags', write_only=True, required=False)

    cover_url = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = [
            'id', 'title', 'slug', 'content', 'cover', 'cover_url', 'summary', 'status', 'author',
            'pub_time', 'update_time', 'views', 'is_top', 'is_show_toc',
            'category', 'category_id', 'tags', 'tag_ids',
            'is_public', 'allow_comments',
        ]
        read_only_fields = ['slug', 'views', 'update_time', 'pub_time', 'author']

    def get_cover_url(self, obj):
        request = self.context.get('request')
        if obj.cover and hasattr(obj.cover, 'url'):
            return request.build_absolute_uri(obj.cover.url)
        return None

    def create(self, validated_data):
        tags = validated_data.pop('tags', [])
        article = super().create(validated_data)
        article.tags.set(tags)
        return article

    def update(self, instance, validated_data):
        tags = validated_data.pop('tags', None)
        article = super().update(instance, validated_data)
        if tags is not None:
            article.tags.set(tags)
        return article
